package com.example.perftool2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    Tool mTool;
    private TextView mTv;
    private PermissionTool mPermTool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTv = findViewById(R.id.text);
        mTool = new Tool(this);
        updateText(mTool.isStarted());
        mTool.setStateChangeListener(new Tool.StateChangeListener() {
            @Override
            public void onChange(boolean isStarted) {
                updateText(isStarted);
            }
        });
        findViewById(R.id.button_start).setOnClickListener( v -> startDump());
        findViewById(R.id.button_stop).setOnClickListener( v -> stopDump());

        mPermTool = new PermissionTool(this, this);
        mPermTool.checkPermission();
    }

    private void updateText(boolean isStarted) {
        mTv.setText(isStarted ? "dump中" : "未开始");
    }

    private void startDump() {
        mTool.startDump();
    }

    private void stopDump() {
        mTool.stopDump();
    }

    private void registerTestAction() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("debug.perf_tool.start");
        registerReceiver(mR, intentFilter);
    }

    private void unRegisterTestAction() {
        unregisterReceiver(mR);
    }

    private BroadcastReceiver mR = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            startDump();
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        final Display disp = getWindowManager().getDefaultDisplay();
        float refreshRate = disp.getRefreshRate();
        Log.i("refreshRate", "refreshRate:" + refreshRate);

        registerTestAction();
    }

    @Override
    protected void onPause() {
        super.onPause();

        unRegisterTestAction();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTool.quit();
    }
}